package com.originit.product.server.controller

import com.originit.product.common.input.CartInput
import com.originit.product.common.output.ProductOutput
import com.originit.product.server.enums.ResultEnum
import com.originit.product.server.exception.ProductException
import com.originit.product.server.service.CategoryService
import com.originit.product.server.service.ProductService
import com.originit.product.server.vo.ProductInfoVO
import com.originit.product.server.vo.ProductVO
import com.originit.product.server.vo.ResultVO
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.*
import javax.validation.Valid

@Api("商品接口")
@RestController
@RequestMapping("/product")
class ProductController {

    val log = LoggerFactory.getLogger(ProductController::class.java)

    @Autowired
    lateinit var categoryService: CategoryService

    @Autowired
    lateinit var productService: ProductService

    @GetMapping("/list")
    fun list():ResultVO<List<ProductVO>>{
        val products = productService.findUpAll()
        val categoryTypeList = products.mapNotNull {
            it.categoryType
        }
        val productTypeMap = products.groupBy { it.categoryType }
        val productVOList = categoryService.findByTypeIn(categoryTypeList)
                .mapNotNull { category ->
                    productTypeMap[category.categoryType]?.mapNotNull {
                        ProductInfoVO(it.productId, it.productName, it.productPrice, it.productDescription, it.productIcon)
                    }?.let {
                        ProductVO(category.categoryName, category.categoryType, it)
                    }
                }
        return ResultVO.success(productVOList)
    }

    @ApiOperation("根据商品id查找商品信息，返回商品信息列表")
    @PostMapping("/listById")
    fun listById(@RequestBody @ApiParam("商品id") orderIds:List<String>):List<ProductOutput>{
        if ( orderIds == null || orderIds.isEmpty()){
            throw ProductException(ResultEnum.PARAM_ERROR, "请传递商品id")
        }
        return productService.findForOrderByIds(orderIds)
    }

    @ApiParam("根据商品id及当前库存更新库存信息")
    @PutMapping("/stock")
    fun minusStockByIds (@Valid @RequestBody productStockList: List<CartInput>, result:BindingResult){
        if (result.hasErrors()){
            log.error("【扣库存】错误={}",result.fieldError?.defaultMessage)
            throw ProductException(ResultEnum.PARAM_ERROR)
        }
        productService.minusStockByIds(productStockList)
    }
}